<script lang="ts" setup>
import { ref, onMounted, computed, watch } from 'vue'
import { Note } from './NoteCard.vue'
import { useAuthStore } from 'stores/authStore'
import { storeToRefs } from 'pinia'

import CommentItem from './CommentItem.vue'
import { NoteCommentDTO, commentAPI, getComments, getNoteImages } from 'src/api'
import { Notify, QInput } from 'quasar'

export interface NoteDialog {
  showing: boolean
  selectedNote?: Note
}

export interface ContentItem {
  id: number
  avatar: string
  nickname: string
  content: string
  createTime: string
  location: string
  children?: ContentItem[]
}

const props = defineProps<{
  selectedNote: Note
}>()

const imageList = ref<Array<string>>([])

const { certified, showLoginDialog } = storeToRefs(useAuthStore())
const emit = defineEmits(['update:like', 'update:collect'])
function updateLike() {
  if (!certified.value && (showLoginDialog.value = true)) return
  const change = !props.selectedNote.liked
  emit('update:like', change)
  //TODO: 需要后端同步更改
}

function updateCollect() {
  if (!certified.value && (showLoginDialog.value = true)) return
  const change = !props.selectedNote.collected
  emit('update:collect', change)
  //TODO: 需要后端同步更改
}

const slide = ref(props.selectedNote.cover)

const width = ref(0)
const fullscreen = ref(false)

const commentInput = ref<QInput>()
// TODO: 需要从后端加载数据
const commentData = ref<ContentItem[]>([])
onMounted(async () => {
  const img = new Image()

  img.src = props.selectedNote.cover
  img.onload = () => {
    width.value = Math.min(600, Math.max(450, img.width * (600 / img.height)))
  }

  await loadImages()

  // commentData.value.push({
  //   id: 1,
  //   avatar:
  //     'https://tse4-mm.cn.bing.net/th/id/OIP-C.Df-VPz22BDyyI0AduHeMzAHaHa?w=207&h=207&c=7&r=0&o=5&dpr=1.3&pid=1.7',
  //   nickname: '小黑子1号',
  //   content: '油饼吧？',
  //   createTime: '03-18',
  //   location: '芜湖',
  //   children: [
  //     {
  //       id: 2,
  //       avatar:
  //         'https://tse4-mm.cn.bing.net/th/id/OIP-C.NZvtyUyQ_eAkZM3B3siIzQHaHa?w=211&h=211&c=7&r=0&o=5&dpr=1.3&pid=1.7',
  //       nickname: '小黑子2号',
  //       content: '能不能荔枝点？',
  //       createTime: '03-18',
  //       location: '芜湖',
  //     },
  //     {
  //       id: 3,
  //       avatar:
  //         'https://tse1-mm.cn.bing.net/th/id/OIP-C.cYez8U_I3Hz1MI0Uw61-_QAAAA?w=174&h=180&c=7&r=0&o=5&dpr=1.3&pid=1.7',
  //       nickname: '小黑子3号',
  //       content: '鸽鸽下的蛋，你别吃！',
  //       createTime: '03-18',
  //       location: '芜湖',
  //     },
  //   ],
  // })

  await loadComments()
})

async function loadImages() {
  imageList.value = await getNoteImages(props.selectedNote.id)
}

async function loadComments() {
  commentData.value = await getComments(props.selectedNote.id)
}

const slideImage = computed(() => {
  return {
    backgroundColor: fullscreen.value ? 'black' : '#fafafa',
    cursor: fullscreen.value ? 'zoom-out' : 'zoom-in',
    backgroundSize: 'contain',
    backgroundRepeat: 'no-repeat',
  }
})

const needBorder = ref(false)
function scrolled(event: Event) {
  const scrollTop = (event.target as Element).scrollTop
  if (scrollTop >= 100) {
    needBorder.value = true
  } else {
    needBorder.value = false
  }
}

const commentDTO = ref<NoteCommentDTO>({
  parentId: 0,
  noteId: props.selectedNote.id,
  content: '',
})
watch(
  () => commentDTO.value.content,
  (value) => {
    if (value[0] != '@') commentDTO.value.parentId = 0
  }
)
async function comment() {
  await commentAPI(commentDTO.value)
  commentDTO.value.content = ''
  Notify.create({
    message: '发送成功',
    position: 'top',
    type: 'positive',
    timeout: 1000,
  })
  await loadComments()
}
</script>

<template>
  <div class="note-container">
    <div
      class="left"
      :style="{
        width: width + 'px',
      }"
    >
      <q-carousel
        animated
        swipeable
        arrows
        v-model="slide"
        v-model:fullscreen="fullscreen"
        navigation
        control-color="orange"
        height="100%"
      >
        <q-carousel-slide
          v-for="(image, index) in imageList"
          :key="index"
          :name="image"
          :img-src="image"
          @click="fullscreen = !fullscreen"
          :style="slideImage"
        />
      </q-carousel>
    </div>

    <div class="right">
      <div :class="'author' + (needBorder ? ' border' : '')">
        <div class="info">
          <q-avatar size="3rem" style="margin-right: 7px"
            ><img :src="selectedNote.authorAvatar"
          /></q-avatar>
          {{ selectedNote.authorNickname }}
        </div>
        <q-btn
          unelevated
          label="关注"
          color="orange-6"
          style="width: 70px; margin-right: 20px"
          rounded
        />
      </div>

      <q-card class="note-scroller" @scroll="scrolled">
        <q-card-section>
          <div class="title">
            {{ selectedNote.title }}
          </div>
          <div style="white-space: pre-line; font-size: 1.1em">
            {{ selectedNote.description || '#' }}
          </div>
        </q-card-section>
        <q-separator inset />
        <q-card-section v-for="(item, index) in commentData" :key="index">
          <comment-item
            :contentItem="item"
            v-model:comment="commentDTO.content"
            v-model:parent-id="commentDTO.parentId"
          >
            <comment-item
              v-for="(chidItem, index) in item.children"
              :content-item="chidItem"
              :key="index"
              v-model:comment="commentDTO.content"
              v-model:parent-id="commentDTO.parentId"
            />
          </comment-item>
          <q-separator inset />
        </q-card-section>
      </q-card>

      <div class="interaction">
        <q-btn-group flat>
          <q-btn
            :text-color="selectedNote.liked ? 'red' : 'grey-5'"
            icon="favorite"
            label="点赞"
            @click="updateLike"
          />
          <q-btn
            :text-color="selectedNote.collected ? 'amber' : 'grey-5'"
            icon="star"
            label="收藏"
            @click="updateCollect"
          />
          <q-btn
            text-color="blue-grey"
            icon="comment"
            label="评论"
            @click="commentInput?.focus()"
          />
          <q-btn text-color="orange" icon="share" label="分享" />
        </q-btn-group>

        <q-input
          ref="commentInput"
          v-model="commentDTO.content"
          placeholder="您的精彩评论"
          rounded
          dense
          standout="bg-orange text-white"
          style="width: 375px; margin: 12px 0"
        >
          <template v-slot:after>
            <q-btn
              color="orange"
              unelevated
              rounded
              label="发送"
              :disable="commentDTO.content === ''"
              @click="comment"
            />
          </template>
        </q-input>
      </div>
    </div>
  </div>
</template>

<style scoped lang="scss">
.note-container {
  @include flex;
  height: 600px;
}

.left {
  height: 100%;
}
.right {
  width: 425px;
  height: 100%;
  border-left: 1px solid #dcdde1;
  .author {
    @include flex($content: space-between);
    padding: 0px 30px;
    height: 100px;

    &.border {
      border-bottom: 0.5px solid rgba(0, 0, 0, 0.1);
    }
    .info {
      cursor: pointer;
      font-weight: bold;
    }
  }

  .interaction {
    @include flex($direction: column);
    height: 122px;
    box-shadow: rgba(0, 0, 0, 0.24) 0px 3px 8px;
    z-index: 0;
  }
}

.note-scroller {
  height: 378px;
  box-shadow: none;
  background: transparent;
  overflow-y: auto;
  padding: 0 15px;

  &::-webkit-scrollbar {
    /*滚动条整体样式*/
    width: 5px; /*高宽分别对应横竖滚动条的尺寸*/
    height: 1px;
  }
  &::-webkit-scrollbar-thumb {
    /*滚动条里面深色条*/
    border-radius: 10px;
    box-shadow: inset 0 0 5px rgba(236, 236, 236, 0.1);
    background: orange;
  }
  &::-webkit-scrollbar-track {
    /*滚动条里面轨道*/
    box-shadow: inset 0 0 5px rgba(236, 236, 236, 0.1);
    border-radius: 10px;
    background: #ededed;
  }

  .title {
    margin-bottom: 20px;
    font-weight: 600;
    font-size: 20px;
    line-height: 32px;
  }
}
</style>
